<?php

namespace app\admin\library;

use app\common\model\User;
use think\Request;
use think\Session;
use lib\Tree;

/***
 * 权限扩展类
 *
 */
class Auth extends \lib\Auth
{

    protected $requestUri = '';
    protected $breadcrumb = [];

    public function __construct()
    {
        parent::__construct();
    }

    public function __get($name)
    {
        return Session::get('user_auth.' . $name);
    }

    public function login($username, $password, $keeptime = 0)
    {
    	if(!$username || !$password){
			return array('code'=>0,'msg'=>'用户名和密码不能为空','data'=>'');
		}
		$user = User::get(['userName'=>$username]);
		if($user){
			if($user['validity']){
				if($user['password'] == md5($password.$user['salt'])){
					$this->autoLogin($user);
					return array('code'=>1,'msg'=>'登录成功','data'=>$user->toArray());
				}else{
					return array('code'=>0,'msg'=>'用户名或密码错误','data'=>'');
				}
			}else{
				return array('code'=>0,'msg'=>'用户名无效','data'=>'');
			}
		}else{
			return array('code'=>0,'msg'=>'用户名不存在','data'=>'');
		}
		
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $admin = User::get(intval($this->id));
        if (!$admin)
        {
            return true;
        }
        Session::delete("user_auth");
        return true;
    }

    /**
     * 自动登录
     * @return boolean
     */
    public function autologin($user)
    {
       /* 更新登录信息 */
		$data = array(
				'id'            	 => $user['id'],
				'loginTotal'         => $user['loginTotal']+1,
				'loginDate'          => time(),
				'loginIp'            => get_client_ip(1),
		);
		$user_model = model('User');
		$user_model->where(array('id'=>$user['id']))->update($data);
		$user = $user_model->where(array('id'=>$user['id']))->with('roles')->find();
	
		/* 记录登录SESSION和COOKIES */
		$auth = array(
				'id'             	 => $user['id'],
				'userName'           => $user['userName'],
				'loginDate'          => $user['loginDate'],
				'enterpriseId'       => $user['enterpriseId'],
				'userProperty'       => $user->userPropertyId,
				'role'               => $user['roles'][0]['roleName'],
				'icon'	             => $user['roles'][0]['roleIcon']?$user['roles'][0]['roleIcon']:'/static/img/basic/nophoto.jpg',	
		);
	
		session('user_auth', $auth);
		session('user_auth_sign', data_auth_sign($auth));
    }


    public function check($name, $uid = '', $relation = 'or', $mode = 'url')
    {
    	return parent::check($name, $this->id, $relation, $mode);
    }

    /**
     * 检测当前控制器和方法是否匹配传递的数组
     *
     * @param array $arr 需要验证权限的数组
     */
    public function match($arr = [])
    {
        $request = Request::instance();
        $arr = is_array($arr) ? $arr : explode(',', $arr);
        if (!$arr)
        {
            return FALSE;
        }

        // 是否存在
        if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr))
        {
            return TRUE;
        }

        // 没找到匹配
        return FALSE;
    }

    /**
     * 检测是否登录
     *
     * @return boolean
     */
    public function isLogin()
    {
     	$user = session('user_auth');
		if (empty($user)) {
			return 0;
		} else {
			return session('user_auth_sign') == data_auth_sign($user) ? $user['id'] : 0;
		}
    }

    /**
     * 获取当前请求的URI
     * @return string
     */
    public function getRequestUri()
    {
        return $this->requestUri;
    }

    /**
     * 设置当前请求的URI
     * @param string $uri
     */
    public function setRequestUri($uri)
    {
        $this->requestUri = $uri;
    }

    public function getGroups($uid = null)
    {
        $uid = is_null($uid) ? $this->id : $uid;
        return parent::getGroups($uid);
    }

    public function getRuleList($uid = null)
    {
        $uid = is_null($uid) ? $this->id : $uid;
        return parent::getRuleList($uid);
    }

    public function getUserInfo($uid = null)
    {
        $uid = is_null($uid) ? $this->id : $uid;

        return $uid != $this->id ? User::get(intval($uid)) : Session::get('user_auth');
    }

    public function getRuleIds($uid = null)
    {
        $uid = is_null($uid) ? $this->id : $uid;
        return parent::getRuleIds($uid);
    }

    public function isSuperAdmin()
    {
        return in_array('*', $this->getRuleIds()) ? TRUE : FALSE;
    }

    /**
     * 获得面包屑导航
     * @param string $path
     * @return array
     */
    public function getBreadCrumb($path = '')
    {
        if ($this->breadcrumb || !$path)
            return $this->breadcrumb;
        $path_rule_id = 0;
        foreach ($this->rules as $rule)
        {
            $path_rule_id = $rule['url'] == $path ? $rule['id'] : $path_rule_id;
        }
        if ($path_rule_id)
        {
            $this->breadcrumb = Tree::instance()->init($this->rules)->getParents($path_rule_id, true);
        }
        return $this->breadcrumb;
    }
    
    /**
     * 获取左侧菜单栏
     *
     * @param array $params URL对应的badge数据
     * @return string
     */
    public function getMenu($url)
    {
     	//获取登录用户ID
		$uid = Session('user_auth.userId');
		//获取用户权限
		$ruleList = $this->getRuleList($uid);
		
		$menu = [];
		//菜单搜寻条件
		$where = ['pid'=>0,'status'=>1,'ismenu'=>1];
		//获取主菜单
		$mainMenu = collection(model('Rule')->where($where)->order('sort')->select())->toArray();
		if($mainMenu && sizeof($mainMenu)>0){
			foreach($mainMenu as $key => $item){
				//用户没有该菜单权限,删除该菜单
				if (!in_array($item['url'],$ruleList)){
					unset($mainMenu[$key]);
					continue;
				}
				$item['url'] = url($item['url']);
				if(url($url) == $item['url']){
					$item['actived'] = true; 
				}
				//录入菜单
				$menu[$item['id']] = $item;
				$menu[$item['id']]['child'] = [];
				//获取子菜单
				$where['pid'] = $item['id'];
				$childMenu = collection(model('Rule')->where($where)->order('sort')->select())->toArray();
				if($childMenu && sizeof($childMenu)>0){
					$menu[$item['id']]['url'] = "javascript:;";
					foreach ($childMenu as $k => $i){
						//用户没有该菜单权限,删除该菜单
						if (!in_array($i['url'],$ruleList)){
							unset($childMenu[$k]);
							continue;
						}
						$i['url'] = url($i['url']);
						if(url($url) == $i['url']){
							$i['actived'] = true;
							$menu[$item['id']]['actived'] = true;
						}
						//录入菜单
						$menu[$item['id']]['child'][] = $i;
					}
				}
				
			}
		}
		return $menu;
    }

}
